import { apiBaseUrl, defaultImg } from "../../../utils/config";
import { time } from "../../../utils/const";
import { dateToLong } from "../../../utils/DateUtils";
import { collectFormIds, saveFormIds, promiseRequest, getOpenId} from "../../../utils/index";
const app = getApp();
var formIdlist = [];
Page({
  data: {
    //是否需要维护商户信息
    modalshow:'',
    backImg: defaultImg,
    backfileId:'',
    nickName:'',
    userTele:'',
    avatarUrl:'',
    rewardName:'',
    rewardPrice:null,
    rewardNum:null,
    hasnickName:false,
    hasuserTele: false,
    helpWayCode: null,
    helpWayText: null,
    picker: ['助力达到指定个数即可领取奖品', '助力个数达到前N名即可领取奖品'],
    grantWaypicker: ['邮寄', '到店兑换'],
    grantWayText: null,
    grantWayCode:null,
    helpNumber:null,
    date: '选择日期',
    pickerTime: time,
    time: '选择时间',
    imgList: [],
    rewardDetail:'',
    rewardDesc:'',
    upimg:false,  //解决上传与预览图片触发onshow事件的bug
    canIUseGetUserProfile: false
  },
//页面加载的时候根据openid查询获取用户的手机号和昵称信息
onLoad(query) {
  this.searchUserInfo();
  if (wx.getUserProfile) {
    this.setData({
      canIUseGetUserProfile: true
    })
  }
},
onShow(){
  if(this.data.upimg){//如果是上传预览图片触发的则不作任何处理直接返回
        return;
  }
  //显示页面的时候判断该页面是不是重预览页面跳转过来的
  let actshareinfo = wx.getStorageSync('actshareinfo');
  actshareinfo = actshareinfo ? JSON.parse(actshareinfo) : null;
  if (actshareinfo){//从预览页面跳过来的，则给页面赋以前填写的值
    this.setDefaultvalue(actshareinfo);
  }
  
},
//页面销毁时提交收集到的formid
onUnload() {
  saveFormIds(formIdlist);
  formIdlist = [];
},
PickerChange(e) {
  this.setData({
    helpWayCode: e.detail.value,
    helpWayText: this.data.picker[e.detail.value]
  })
},
grantWayChange(e) {
  this.setData({
    grantWayCode: e.detail.value,
    grantWayText: this.data.grantWaypicker[e.detail.value]
  })
},
TimeChange(e) {
  console.log(e.detail.value);
  let hours = e.detail.value;
  if (hours.length == 1) {
    hours = "0" + hours;
  }
  this.setData({
    time: hours + ":00"
  })
},
DateChange(e) {
  this.setData({
    date: e.detail.value
  })
},
ChooseImage() {
  let that = this;
  this.data.upimg = true;
  wx.chooseImage({
    count: 9, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album'], //从相册选择
    success: (res) => {
      if (this.data.imgList.length != 0) {
        this.setData({
          imgList: this.data.imgList.concat(res.tempFilePaths)
        })
      } else {
        this.setData({
          imgList: res.tempFilePaths
        })
      }
      for (var i = 0; i < res.tempFilePaths.length; i++) {
        wx.uploadFile({
          url: apiBaseUrl + '/wxa/actshare/uploadImag',
          filePath: res.tempFilePaths[i],
          name: 'img',
          header: {
            "Content-Type": "multipart/form-data",
            'token': wx.getStorageSync('token')
          },
          formData: {
            'uploadType': 'share'
          },
          success(res) {
            const data = JSON.parse(res.data)
            console.log(data);
            if (that.data.rewardDetail == '') {
              // that.setData({
              //   rewardDetail: data.fileId
              // })
              that.data.rewardDetail = data.fileId
            } else {
              // that.setData({
              //   rewardDetail: that.data.rewardDetail + "," + data.fileId
              // })
              that.data.rewardDetail = that.data.rewardDetail + "," + data.fileId
            }
          }
        })
      }
    }
  });
},
ViewImage(e) {
  this.data.upimg = true;
  wx.previewImage({
    urls: this.data.imgList,
    current: e.currentTarget.dataset.url
  });
},
DelImg(e) {
  wx.showModal({
    title: '主人',
    content: '确定要删除这段记忆吗？',
    cancelText: '再看看',
    confirmText: '再见',
    success: res => {
      if (res.confirm) {
        this.data.imgList.splice(e.currentTarget.dataset.index, 1);
        this.setData({
          imgList: this.data.imgList
        })
        let temprewardDetail = this.data.rewardDetail.split(",");
        let temprewardDetailStr = '';
        if (temprewardDetail && temprewardDetail.length>0){
          temprewardDetail.splice(e.currentTarget.dataset.index,1);
          for (var i = 0; i < temprewardDetail.length; i++) {
            if (i == 0) {
              temprewardDetailStr = temprewardDetail[i];
            } else {
              temprewardDetailStr = temprewardDetailStr+ ","+temprewardDetail[i]
            }
          }
          this.data.rewardDetail = temprewardDetailStr;
        }
      }
    }
  })
},
hideModal(e) {
this.setData({
  modalshow: ''
})
},
//根据openId修改用户信息,用户昵称
updateUserInfo(userInfo){
  let requestObj = {
    url: '/wxa/actthirdparty/update',
    method: 'post',
	  dataobj: userInfo,
  };
  promiseRequest(requestObj).then((res) => {
     if (res.code == 200) {
        this.setData({
          hasnickName: true
        })    
      }
  }).catch((errMsg) => {
  });
},
//根据openId查询用户昵称和用户手机号信息
searchUserInfo() {
  let openid = getOpenId();
  let requestObj = {
    url: '/wxa/actthirdparty/detailCache',
    method: 'post',
    dataobj: { openid: openid},
  };
  promiseRequest(requestObj).then((res) => {
    if (res.code == 200) {
      if (res.data.nickName != null) {
        this.setData({
          nickName: res.data.nickName,
          avatarUrl: res.data.avatarUrl,
          hasnickName: true
        })
        if (res.data.shopName == '' || res.data.shopName == null) {
          //设置是否需要弹出维护商家信息的提示
          this.setData({
            modalshow: 'show'
          })
        }
      }
      if (res.data.userTele != null) {
        this.setData({
          userTele: res.data.userTele,
          hasuserTele: true
        })
      }
    }
  }).catch((errMsg) => {
  });
},
getUserProfile(e) {
  // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认
  // 开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
  let that = this;
  wx.getUserProfile({
    desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
    success: (res) => {
      let openid = getOpenId();
      let userinfo = res.userInfo;
      console.log(userinfo);
      let param = { openid:openid,nickName: userinfo.nickName, avatarUrl: userinfo.avatarUrl, gender: userinfo.gender, language: userinfo.language }
      that.setData({
        nickName: userinfo.nickName,
        avatarUrl: userinfo.avatarUrl
      })
      that.updateUserInfo(param)
    }
  })
},
getUserInfo(e) {
  // 不推荐使用getUserInfo获取用户信息，预计自2021年4月13日起，getUserInfo将不再弹出弹窗，并直接返回匿名的用户个人信息
  let openid = getOpenId();
  let userinfo = e.detail.userInfo;
  let param = { openid:openid,nickName: userinfo.nickName, avatarUrl: userinfo.avatarUrl, gender: userinfo.gender, language: userinfo.language }
  this.setData({
        nickName: userinfo.nickName,
        avatarUrl: userinfo.avatarUrl
  })
  this.updateUserInfo(param)
},
//获取用户手机号触发的事件
getPhoneNumber(e) {
  //同意获取手机信息
  if (e.detail.errMsg == 'getPhoneNumber:ok'){
    wx.checkSession({
      success: () => {
         this.decodeUserPhone(e.detail.iv, e.detail.encryptedData);
      },
      fail: () => {
        // 重新授权
        // getToken().then(() => {
        //   this.decodeUserPhone(e.detail.iv, e.detail.encryptedData);
        // })
      }
    })
  }else{

  }
},
decodeUserPhone(iv, encryptedData) {
  let requestObj = {
    url: '/wxa/user/decodeUser',
    method: 'post',
    dataobj: { iv: iv, encryptedData:encryptedData},
  };
  promiseRequest(requestObj).then((res) => {
    if (res.data) {
      this.setData({
        userTele: res.data.phoneNumber,
        hasuserTele: true
      })
    } else {
      wx.showModal({
        title: '提示',
        showCancel: false,
        content: '自动获取手机号码失败，请手动输入',
        success: (res) => {
          wx.navigateTo({
            url: '/pages/compent/telCheck/telCheck'
          })
        }
      })
    }
  }).catch((errMsg) => {
  });
},
bindrewardName(e){
  this.setData({
    rewardName: e.detail.value
  })  
},
bindrewardNum(e) {
  this.setData({
    rewardNum: e.detail.value
  })
},
bindrewardPrice(e) {
  this.setData({
    rewardPrice: e.detail.value
  })
},
bindhelpNumber(e) {
  this.setData({
    helpNumber: e.detail.value
  })
},
bindrewardDesc(e) {
  this.setData({
    rewardDesc: e.detail.value
  })
},
//保存分享活动信息
saveshare(e) {
  //点击发布按钮的时候手机fomid
  collectFormIds(e, formIdlist);
  let that = this;
  let backImg = this.data.backfileId;//背景图附件id
  let rewardName = this.data.rewardName;//奖励名称
  let rewardNum = this.data.rewardNum;//奖励数量
  let hasNum = this.data.rewardNum;//奖励剩余数量
  let rewardPrice = this.data.rewardPrice;//奖励价值
  let helpWayText = this.data.helpWayText;//助力方式名称
  let helpWayCode = this.data.helpWayCode;//助力方式编码
  let grantWayCode = this.data.grantWayCode;//奖励发放方式编码
  let grantWayText = this.data.grantWayText;//奖励发放方式名称
  let helpNumber = this.data.helpNumber;//助力数量
  let rewardDetail = this.data.rewardDetail;//奖励详情图片附件id多个用逗号隔开
  let rewardDesc = this.data.rewardDesc;//奖励详情文字描述
  let endTime = this.data.date + " " + this.data.time;//活动结束时间
  let nickName = this.data.nickName;//用户昵称
  let userTele = this.data.userTele;//用户电话
  let avatarUrl = this.data.avatarUrl//用户头像

  if (nickName==''){
    wx.showToast({
      title: '用户昵称不能为空!',
      icon: 'none'
    });   
    return; 
  }
  if (userTele == '') {
    wx.showToast({
      title: '用户手机号不能为空!',
      icon: 'none'
    });
    return; 
  }
  if (rewardName == '') {
    wx.showToast({
      title: '奖励名称不能为空!',
      icon: 'none'
    });
    return; 
  }
  if (rewardPrice == null) {
    wx.showToast({
      title: '奖励价值不能为空!',
      icon: 'none'
    });
    return;
  }  
  if (rewardNum == null) {
    wx.showToast({
      title: '奖励个数不能为空!',
      icon: 'none'
    });
    return; 
  } 

  if (helpWayText == null) {
    wx.showToast({
      title: '助力方式不能为空!',
      icon: 'none'
    });
    return; 
  }
  if (helpNumber == null) {
    wx.showToast({
      title: '助力数量不能为空!',
      icon: 'none'
    });
    return;
  }
  if (this.data.date == '选择日期') {
    wx.showToast({
      title: '结束日期不能为空!',
      icon: 'none'
    });
    return;
  }
  if (this.data.time == '选择时间') {
    wx.showToast({
      title: '结束时间不能为空!',
      icon: 'none'
    });
    return;
  }
  if (grantWayText == null) {
    wx.showToast({
      title: '奖励发放方式不能为空!',
      icon: 'none'
    });
    return; 
  } 
  //活动结束时间判断不能小于当前时间
  let jssjtime = dateToLong(new Date(endTime));
  let nowtime = dateToLong(new Date())+3600*1000*2;
  if (jssjtime <= nowtime) {
    wx.showToast({
      title: '活动结束时间最短为两小时之后!',
      icon: 'none'
    });
    return;
  }
  //确认发起分享活动
  var actshare = { backImg: backImg, nickName: nickName, userTele: userTele, avatarUrl: avatarUrl, rewardName: rewardName, rewardNum: rewardNum, hasNum: hasNum, rewardPrice: rewardPrice, helpWayText: helpWayText, helpWayCode: helpWayCode, grantWayCode: grantWayCode, grantWayText: grantWayText, helpNumber: helpNumber, rewardDetail: rewardDetail, rewardDesc: rewardDesc, endTime: endTime };
  wx.showModal({
    title: '确认发布分享吗?',
    content: '确认发布后,无法再编辑修改!',
    success(res) {
      if (res.confirm) {
        that.suresaveshare(actshare);
      } else if (res.cancel) {
       
      }
    }
  })
},
suresaveshare(actshare){
  let requestObj = {
    url: '/wxa/actshare/saveShare',
    method: 'post',
    dataobj: actshare,
  };
  promiseRequest(requestObj).then((res) => {
    if (res.code == 200) {
      //保存成功后删除掉本地的活动信息缓存
      wx.removeStorageSync("actshareinfo");
      let actId = res.data.actId;
      wx.redirectTo({
        url: '/pages/compent/shareDetail/shareDetail?actId=' + actId
      })
    }
  }).catch((errMsg) => {
  });
},

//活动预览
sharepreview(){
  let backImg = this.data.backImg;//背景图附件id
  let backfileId = this.data.backfileId;//背景图附件id
  let imgList = this.data.imgList;
  let rewardName = this.data.rewardName;//奖励名称
  let rewardNum = this.data.rewardNum;//奖励数量
  let rewardPrice = this.data.rewardPrice;//奖励价值
  let helpWayText = this.data.helpWayText;//助力方式名称
  let helpWayCode = this.data.helpWayCode;//助力方式编码
  let grantWayCode = this.data.grantWayCode;//奖励发放方式编码
  let grantWayText = this.data.grantWayText;//奖励发放方式名称
  let helpNumber = this.data.helpNumber;//助力数量
  let rewardDetail = this.data.rewardDetail;//奖励详情图片附件id多个用逗号隔开
  let rewardDesc = this.data.rewardDesc;//奖励详情文字描述
  let nickName = this.data.nickName;//用户昵称
  let userTele = this.data.userTele;//用户电话
  let avatarUrl = this.data.avatarUrl;//用户头像
  let date = this.data.date == '选择日期' ? '' : this.data.date;//用户选择的日期
  let time = this.data.time == '选择时间' ? '' : this.data.time;//用户选择的时间
  var actshareinfo = { backImg: backImg, backfileId: backfileId, imgList: imgList, nickName: nickName, userTele: userTele, avatarUrl: avatarUrl, rewardName: rewardName, rewardNum: rewardNum, rewardPrice: rewardPrice, helpWayText: helpWayText, helpWayCode: helpWayCode, grantWayCode: grantWayCode, grantWayText:grantWayText,helpNumber: helpNumber, rewardDetail: rewardDetail, rewardDesc: rewardDesc, date:date,time:time};
  wx.setStorageSync('actshareinfo', JSON.stringify(actshareinfo));
  //跳转到预览页面时,把upimg设置为初始值
  this.data.upimg = false;
  wx.navigateTo({
    url: '/pages/compent/sharePreview/sharePreview'
  })
},
//上传背景图
uploadBackImg(){
  let that = this;
  this.data.upimg = true;
  console.log(this.data.upimg);
  wx.chooseImage({
    count: 1,
    sizeType: ['original', 'compressed'],
    sourceType: ['album'],
    success(res) {
      const tempFilePaths = res.tempFilePaths
      console.log(tempFilePaths[0]);
      wx.uploadFile({
        url: apiBaseUrl +'/wxa/actshare/uploadImag',
        filePath: tempFilePaths[0],
        name: 'img',
        header: {
          "Content-Type": "multipart/form-data",
          'token': wx.getStorageSync('token')
        },
        formData: {
          'uploadType': 'share'
        },
        success(res) {
          const data = JSON.parse(res.data)
          console.log(data);
          that.setData({
            backImg: tempFilePaths[0],
            backfileId: data.fileId
          })  
        }
      })
    }
  })
},
setDefaultvalue(actshareinfo){
  this.setData({
    backImg: actshareinfo.backImg ? actshareinfo.backImg:'',
    backfileId: actshareinfo.backfileId ? actshareinfo.backfileId:'',
    rewardName: actshareinfo.rewardName ? actshareinfo.rewardName:'',
    rewardNum: actshareinfo.rewardNum ? actshareinfo.rewardNum:null,
    rewardPrice: actshareinfo.rewardPrice ? actshareinfo.rewardPrice:null,
    helpWayText: actshareinfo.helpWayText ? actshareinfo.helpWayText:'',
    helpWayCode: actshareinfo.helpWayCode ? actshareinfo.helpWayCode:'',
    grantWayCode: actshareinfo.grantWayCode ? actshareinfo.grantWayCode:null,
    grantWayText: actshareinfo.grantWayText ? actshareinfo.grantWayText:null,
    helpNumber: actshareinfo.helpNumber ? actshareinfo.helpNumber:null,
    rewardDetail: actshareinfo.rewardDetail ? actshareinfo.rewardDetail:'',
    rewardDesc: actshareinfo.rewardDesc ? actshareinfo.rewardDesc:'',
    date: actshareinfo.date == '' ? '选择日期' : actshareinfo.date,
    time: actshareinfo.time == '' ? '选择时间': actshareinfo.time,
    endTime: actshareinfo.date + " " + actshareinfo.time,
    nickName: actshareinfo.nickName ? actshareinfo.nickName:null,
    userTele: actshareinfo.userTele ? actshareinfo.userTele:null,
    avatarUrl: actshareinfo.avatarUrl ? actshareinfo.avatarUrl:'',
    imgList: actshareinfo.imgList ? actshareinfo.imgList:[]
  })
},
//去完善商户信息
shopdetail(){
  this.setData({
    modalshow: ''
  })
  wx.navigateTo({
   url: '../../compent/shop/shop',
  })
},
})